package com.situ.project1.controller;

import com.github.pagehelper.PageInfo;
import com.situ.project1.pojo.Customer;
import com.situ.project1.service.CustomerService;
import com.situ.project1.util.PaginateInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author:yzy
 * @date:2024/8/10
 */
@RestController
@RequestMapping(value = "/api/customer", produces = "application/json;charset=utf-8")
public class CustomerController {
    private CustomerService customerService;

    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    //查询全部以及修改
    @GetMapping
    public Map<String, Object> getAll(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "2147483647") Integer pageSize,
            Customer customer
    ) {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 10) {
            pageSize = Integer.MAX_VALUE;
        }
        PaginateInfo pi = new PaginateInfo(pageNo, pageSize);

        List<Customer> customers = customerService.getAll(pi, customer);
        PageInfo<Customer> pageInfo = new PageInfo<>(customers);
        Map<String, Object> map = Map.of("total", pageInfo.getTotal(), "pageNo", pageInfo.getPageNum(), "pageSize", pageInfo.getPageSize());
        return Map.of("success", true, "rows", customers, "pi", map);
    }

    //新增员工
    @PostMapping
    public Map<String, Object> add(@RequestBody Customer customer) {

        if (!customer.getCustomerId().isEmpty()
                && !customer.getPhone().isEmpty()
                && !customer.getName().isEmpty()
                && !customer.getWork().isEmpty()
                && !customer.getAddress().isEmpty()

        ) {
            boolean success = customerService.add(customer);
            return Map.of("success", success);
        }else {
            return Map.of("success", false);
        }
    }

    //更新客户
    @PutMapping
    public Map<String, Object> update(@RequestBody Customer customer) {
        boolean success = customerService.update(customer);
        return Map.of("success", success);
    }

    //删除客户
    @DeleteMapping
    public Map<String, Object> delete(@RequestBody Integer ids[]) {
        boolean success = customerService.delete(ids);
        return Map.of("success", success);
    }

//    根据登录的账号来查询客户的信息
    @GetMapping("/user-customer")
    public Map<String, Object> getUserCustomer(@RequestParam String username) {
        Customer customer = customerService.getUserCustomer(username);
        return Map.of("success", true, "customer", customer);
    }
}
